#!/bin/bash

KEY="$1"
BASE_URL="$2"
SIGNATURE_QUERY_KEY_NAME="$3"
POLICY_QUERY_KEY_NAME="$4"
LIFE_TIME="$5"
EPOCH=$(date +%s)
EPOCH_MS=$((EPOCH * 1000))
URL_EXPIRE=$((EPOCH_MS + (LIFE_TIME * 1000)))

if [[ -z "${KEY}" || -z "${BASE_URL}" || -z "${SIGNATURE_QUERY_KEY_NAME}" || -z "${POLICY_QUERY_KEY_NAME}" || -z "${LIFE_TIME}" ]]
then
	echo "Usage: $0 [HMAC_KEY] [BASE_URL] [SIGNATURE_QUERY_KEY_NAME] [POLICY_QUERY_KEY_NAME] [LIFE TIME SECONDS]"
	echo ""
	echo "Example:"
	echo "    $0 ome_is_the_best ws://host:3333/app/stream signature policy 10"
	echo "    => ws://host:3333/app/stream?policy=e1widXJsX2V4cGlyZVwiOjE2MDQzNzc1MjAxNzh9&signature=rXfU1z1ynBTfK-q6_HM_I9fPzRs"

	exit
fi

# 1. Perform base64url() for POLICY (RFC 4648 5.)
# POLICY_BASE64 = base64url(POLICY)
POLICY="{\"url_expire\":$URL_EXPIRE}"
POLICY_BASE64=$(echo -n "${POLICY}" | base64 -w 0)
POLICY_BASE64=${POLICY_BASE64%==}
POLICY_BASE64=${POLICY_BASE64%=}
POLICY_BASE64=${POLICY_BASE64//+/-}
POLICY_BASE64=${POLICY_BASE64//\//_}

# 2. Generates an URL such as "ws://ome_host:3333/app/stream?policy=${POLICY_BASE64}"
# Check if BASE_URL has a question mark
[ "${BASE_URL#*\?}" = "${BASE_URL}" ] && QS_SEPARATOR="?" || QS_SEPARATOR="&"
POLICY_URL="${BASE_URL}${QS_SEPARATOR}policy=${POLICY_BASE64}"

# 3. Perform sha1(base64url()) for SIGNATURE (RFC 4648 5.)
# SHA1 = sha1(POLICY_URL)
SHA1=$(echo -n "${POLICY_URL}" | openssl dgst -sha1 -hmac "${KEY}")
# Remove the "(stdin) =" prefix which is generated by openssl
SHA1=${SHA1#*= }
# SIGNATURE = base64url(SHA1)
SIGNATURE=$(echo -n "${SHA1}" | xxd -r -p | base64 -w 0)
SIGNATURE=${SIGNATURE%==}
SIGNATURE=${SIGNATURE%=}
SIGNATURE=${SIGNATURE//+/-}
SIGNATURE=${SIGNATURE//\//_}

# 4. Create a whole URL
RESULT="${POLICY_URL}&${SIGNATURE_QUERY_KEY_NAME}=${SIGNATURE}"
echo "[URL] "${RESULT}

# 5. For SRT, percent encode
URLENCODED=$(python3 -c "import urllib.parse; print(urllib.parse.quote('${RESULT}'))")
echo "[Percent encoded URL] "${URLENCODED} 